import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, ScrollView } from '@tarojs/components'
import { AtInputNumber, AtMessage } from 'taro-ui'
import isFunction from 'lodash/isFunction'
import { connect } from 'react-redux'
import { goToLogin } from '@/utils/login'
import classnames from 'classnames'
import { getSkuInfo, createCart } from '@/api/goods'
import Iconfont from '../Iconfont'
import { Props, State } from './types'

import './index.scss'

@connect<any>(({ user }) => ({ user }))
export default class Sku extends Component<Props, State> {
  constructor(props) {
    super(...arguments)
    let selectSku
    if (props.sku) {
      selectSku = new Array(props.sku.length)
    }
		console.log('传递进来的props',props)
    this.state = {
      number: 1,
      visible: props.visible,
      sku: props.sku,
      goodsInfo: props.goodsInfo,
      selectSku,
      isCurrentSku: true,
      goodsSkuId: '',
      maxNumber: props.maxNumber,
			selectStore:props.selectStore,
      jihuasuanInfo:props.jihuasuanInfo,
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { isCurrentSku } = this.state
    const {
      visible,
      goodsInfo,
      currentSku,
			selectStore,
      jihuasuanInfo
    } = nextProps
    // 单商品sku 重新赋值
    if (currentSku.length > 0) {
      this.setState({
        goodsInfo,
        selectSku: currentSku,
        isCurrentSku: false
      })
    }

    if (!visible) {
      this.close()
      return
    }
    if (!this.state.visible) {
      this.setState({
        visible: true,
        jihuasuanInfo,
				selectStore,

      })
    }
  }

  close() {
    const {
      selectSku,
      visible,
      number,
      goodsInfo
    } = this.state
    if (visible) {
      this.setState({
        visible: false
      })
      if (isFunction(this.props.onClose)) {
        const newSelectSku = [...selectSku.values()].every(v => v) ? selectSku : []
        this.props.onClose(newSelectSku, number, goodsInfo)
      }
    }
  }

  getSkuInfo(skuItemIds) {
		let { selectStore ,jihuasuanInfo} = this.state
    const {
      goodsInfo
    } = this.state
    let data = {
      goodsId: goodsInfo.id,
      skuItemIds,
			storeCode:selectStore.storeCode
    }
    if(jihuasuanInfo && jihuasuanInfo.jihuasuanId){
      data.jihuasuanId = jihuasuanInfo.jihuasuanId
      data.jihuasuanGoodsId = jihuasuanInfo.jihuasuanGoodsId
    }
    getSkuInfo(data).then(res => {
      const data = res.data['data']
			console.log('data',data)
			console.log('sku里面执行',data.salePrice)
      this.setState({
        goodsSkuId: data.goodsSkuId,
        goodsInfo: {
          ...goodsInfo,
          stock: data.stock,
          stockTips: data.stockTips,
          thumbUrl: data.thumbUrl,
          salePrice: data.salePrice,
          goodsSkuId: data.goodsSkuId,
          originalPrice: data.originalPrice
        }
      })
    })
  }

  closeEvent(e) {
    this.close()
    e.stopPropagation()
  }

  handleChange(n: number) {
    const { maxNumber } = this.state
    if (maxNumber != 0 && n > maxNumber) {
      return Taro.showToast({
        title: '超出相同订单最多可销售次数',
        icon: 'none'
      })
    }
    this.setState({
      number: n
    })
  }

  // 点击sku
  selectSkuProperty(n) {
    const selectIndex = n[0]
    const { selectSku, sku } = this.state
    const selectVal = sku[selectIndex]
    const property = selectVal.items[n[1]]
    let currentSelectSku = selectSku

    if (currentSelectSku[selectIndex] && property.id === currentSelectSku[selectIndex].property.id) {
      currentSelectSku[selectIndex] = null
    } else {
      currentSelectSku[selectIndex] = {
        id: selectVal.id,
        name: selectVal.name,
        property
      }
    }

    const skuItemIds = currentSelectSku.filter(v => v && v.property.id).map(v => v.property.id)
    this.getSkuInfo(skuItemIds.join(','))

    console.log('currentSelectSku: ', currentSelectSku);
    this.setState({
      selectSku: currentSelectSku
    })
  }

  private addStatus: boolean = false
  nextHandle(directBuy, e) {

    // if (this.addStatus) return
    // this.addStatus = true
    const { selectSku, sku, goodsInfo, number, goodsSkuId,selectStore,jihuasuanInfo } = this.state
    console.log('jihuasuanInfo',jihuasuanInfo)
    const { user } = this.props
    if(jihuasuanInfo && jihuasuanInfo.jihuasuanId && directBuy == 0){
      Taro.showToast({
				title: '当前商品为集划算商品，无法加入购物车。',
				icon: 'none',
				duration: 2000,
			})
			return
    }
    if (!user.userInfo.accessId) {
      goToLogin()
      return
    }
		if (!selectStore.storeCode) {  // 加入购物车的时候需要先选择下单门店
			Taro.showToast({
				title: '请先选择下单门店！',
				icon: 'none',
				duration: 2000,
			})
			return
    }

    if (selectSku) {
      for (let i = 0, len = selectSku.length; i < len; i++) {
        const selectInfo = selectSku[i]
        if (!selectInfo) {
          Taro.atMessage({
            'message': `请选择${sku[i].name}`
          })
          // this.addStatus = false
          return
        }
      }

      if (!goodsInfo.stock) {
        // Taro.atMessage({
        //   'message': goodsInfo.stockTips || '库存空空如也'
        // })
        return
      }
      if (!goodsInfo.goodsSkuId) {
        return
      }
      createCart({
        goodsData: JSON.stringify([{
          goodsId: goodsInfo.id,
          goodsSkuId:goodsSkuId || goodsInfo.goodsSkuId,
          number,
          itemType: 1,
          directBuy
        }]),
				storeCode:selectStore.storeCode
      }).then(res => {
        const data = res.data['data']
        if (!directBuy) {
          Taro.atMessage({
            'message': '添加成功'
          })
        } else {

          let url = '/pages/order/index/index?cartIds=' + JSON.stringify(data.cartIds)+'&store='+ JSON.stringify(selectStore)
          if(jihuasuanInfo.jihuasuanId){
            let {
              jihuasuanId,
              pMobile,
              ppMobile,
              jihuasuanGoodsId,
              jihuasuanSource
            } = jihuasuanInfo
            url = `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(selectStore)}&jihuasuanId=${jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&jihuasuanGoodsId=${jihuasuanGoodsId}&jihuasuanSource=${jihuasuanSource}`
          }
          // console.log(this.props.distribution.urlStoreCode, this.props.distribution.storeCode);
          if (this.props.distribution && (this.props.distribution.urlStoreCode === this.props.distribution.storeCode)) {
            url += '&distribution=' + JSON.stringify(this.props.distribution)
          }
          // 去购买，跳转页面
          Taro.navigateTo({
            url
          })
        }
        // this.addStatus = false
        this.close()
      }).catch(e => {
        // this.addStatus = false
      })
    }
    e.stopPropagation()
  }

  render() {
    let distribution = {}
    if (this.props.distribution) {
      distribution = JSON.parse(JSON.stringify(this.props.distribution))
    }
    // console.log('distribution: ', distribution);
    const {
      visible,
      sku,
      goodsInfo,
      selectSku,
      jihuasuanInfo
    } = this.state
    return visible ? (
      <View className={`sku-content ${visible ? 'show' : ''}`} onTouchMove={(e) => e.stopPropagation()} >
        <AtMessage />
        <View className='sku-mask' onClick={(e) => this.closeEvent(e)}></View>
        <View className='sku-container'>
          <View className='sku-close-btn' onClick={(e) => this.closeEvent(e)}><Iconfont size='32' color='#ccc' name='icon-guanbiX' /></View>
          <View className='sku-goods-info'>
            <Image className='sku-goods-image' src={goodsInfo.thumbUrl} />
            <View className='sku-goods-wrap'>
              <View className='sku-goods-name'>{goodsInfo.name}</View>
              <View className='sku-goods-price'>￥{Number(goodsInfo.salePrice)}</View>
              <View className='sku-goods-stock'>库存：{goodsInfo.stock}</View>
            </View>
          </View>
          <View className='sku-goods-property'>
            <ScrollView scrollY className='sku-goods-property-item'>
              {
                sku.map((s, idx) => {
                  return (
                    <View key={s.id} className='sku-goods-property-li'>
                      <View className='sku-child-name'>{s.name}</View>
                      <View className='sku-goods-property-val'>
                        {
                          s.items.map((skuProperty, skuPropertyIdx) => {
                            return (
                              <View
                                key={skuProperty.id}
                                onClick={() => this.selectSkuProperty([idx, skuPropertyIdx])}
                                className={
                                  ['sku-goods-property-vali', (selectSku[idx] && selectSku[idx].property.id === skuProperty.id) ? 'act' : ''].join(' ')
                                }
                              >
                                {skuProperty.name}
                              </View>
                            )
                          })
                        }
                      </View>
                    </View>
                  )
                })
              }
            </ScrollView>
            <View className='sku-goods-number-cont'>
              <View className='sku-child-name'>购买数量</View>
              <AtInputNumber
                type='number'
                min={1}
                max={Number(goodsInfo.stock)}
                step={1}
                value={this.state.number}
                onChange={this.handleChange.bind(this)}
              />
            </View>
          </View>
          {
            goodsInfo && goodsInfo.isOnSale == 1 ?
              <View className={classnames('sku-handle',(jihuasuanInfo && jihuasuanInfo.jihuasuanId) && 'cheap-handle')}>
                {(distribution != null && distribution.isDistribution === '1') || (jihuasuanInfo && jihuasuanInfo.jihuasuanId) ? '' :
                  <View className={classnames('btn add-cart', goodsInfo.stock == 0 && 'disabled')} onClick={(e) => this.nextHandle(0, e)}>加入购物车</View>
                }
                <View className={classnames('btn buy', (jihuasuanInfo && jihuasuanInfo.jihuasuanId) && 'cheap-btn',goodsInfo.stock == 0 && 'disabled')} onClick={(e) => this.nextHandle(1, e)}>立即购买</View>
              </View> :
              <View className='sku-handle'>
                <View className='btn gray'>已下架</View>
              </View>
          }
        </View>
      </View>
    ) : null
  }
}
